package com.neurotech.pcc.widgets

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Looper
import android.support.v4.content.ContextCompat
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import com.neurotech.pcc.R

/**
 * Created by shenhua on 2018/10/11.
 * @author shenhua
 *         Email shenhuanet@126.com
 */
class IconView @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null, defAttrStyle: Int = 0)
    : View(context, attributeSet, defAttrStyle) {

    private var bgPaint: Paint = Paint()
    private var minWidth = 0
    private var dotPaint: Paint

    init {
        bgPaint.style = Paint.Style.FILL
        bgPaint.isAntiAlias = true
        bgPaint.color = ContextCompat.getColor(context, R.color.colorPrimary)
        if (background != null) {
            setBackgroundColor(Color.TRANSPARENT)
        }
        dotPaint = Paint(bgPaint)
        dotPaint.color = Color.TRANSPARENT
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        minWidth = Math.min(measuredWidth, measuredHeight)
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.translate(minWidth / 2f, minWidth / 2f)
        canvas?.drawCircle(0f, 0f, minWidth / 2f, bgPaint)

        val x = (minWidth / 2f * Math.cos(45 * Math.PI / 180))
        val y = (minWidth / 2f * Math.sin(45 * Math.PI / 180))
        canvas?.drawCircle(x.toFloat(), y.toFloat(), TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, minWidth / 7f, resources.displayMetrics), dotPaint)

//        canvas?.drawText("8", 0f, 0f, dotPaint)
    }

    /**
     * 在线
     */
    fun online() {
        dotPaint.color = ContextCompat.getColor(context, R.color.colorOnline)
        refresh()
    }

    /**
     * 离线
     */
    fun offline() {
        dotPaint.color = ContextCompat.getColor(context, R.color.colorOffline)
        refresh()
    }

    /**
     * 未知状态
     */
    fun unknow() {
        dotPaint.color = Color.TRANSPARENT
        refresh()
    }

    fun color(color: Int) {
        bgPaint.color = color
        refresh()
    }

    private fun refresh() {
        if (Looper.getMainLooper() == Looper.myLooper()) {
            invalidate()
        } else {
            postInvalidate()
        }
    }

}
